import { Modal, Upload, message } from 'antd';
import { useState, useCallback, useMemo } from 'react';
import useRefState from './useRefState';
import * as api from './services';
import { exceptSpace } from '@/utils';

export default function useMakeList() {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [fileList, setFileList] = useState([]);

  // --- 列表请求参数 ---
  const [paginationRef, setPagination] = useRefState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  // --- 额外的参数，通常是表单元素的值 ---
  const [extraParamsRef, setExtraParams] = useRefState({});

  // --- 列表 ---
  const [list, setList] = useState([]);

  // --- loading状态 ---
  const [loading, setLoading] = useState(false);
  const [downloadPending, setDownloadPending] = useState(false);
  const [uploadPending, setUploadPending] = useState(false);

  // --- 处理请求参数 ---
  const getQueryParams = useCallback(
    () =>
      exceptSpace({
        ...extraParamsRef.current,
        pageNum: paginationRef.current.current || 1,
        pageSize: paginationRef.current.pageSize || 10,
      }),
    [],
  );

  // --- 删除后重新计算分页 ---
  const calcPageAfterDelete = useCallback(
    delCount => {
      setPagination(prev => {
        const newTotal = prev.total - delCount;
        let newTotalPages = Math.ceil(newTotal / prev.pageSize);
        newTotalPages = newTotalPages <= 0 ? 1 : newTotalPages;
        return {
          ...prev,
          total: newTotal,
          current: prev.current > newTotalPages ? newTotalPages : prev.current,
        };
      });
    },
    [setPagination],
  );

  // --- 获取列表 ---
  const getList = useCallback(() => {
    setLoading(true);
    api
      .getList(getQueryParams())
      .then(res => {
        if (res.success) {
          setPagination(prev => ({ ...prev, total: res?.data?.total || 0 }));

          const { pageSize = 10, current = 1 } = paginationRef.current;
          setList(
            res?.data?.records?.map((item, index) => ({
              ...item,
              __index: (current - 1) * pageSize + index + 1,
            })) || [],
          );
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }, [getQueryParams, setPagination]);

  // --- 下载表格 ---
  const downloadExcel = useCallback(() => {
    const p = getQueryParams();
    p.selections = selectedRowKeys.join(',');

    setDownloadPending(true);
    api.downloadExcel(p).finally(() => {
      setDownloadPending(false);
    });
  }, [getQueryParams, selectedRowKeys]);

  // --- 上传excel ---
  const uploadExcel = useCallback(
    e => {
      e.stopPropagation();
      if (fileList.length > 0) {
        setUploadPending(true);
        api
          .uploadExcel({ file: fileList[0].originFileObj })
          .then(res => {
            if (res.success) {
              setFileList([]);
              getList();
            } else {
              setFileList(prev => [
                {
                  ...prev[0],
                  response: res?.message || '导入失败，请重试',
                  status: 'error',
                },
              ]);
            }
          })
          .catch(err => {
            message.warn(err?.message || '导入失败，请重试');
            setFileList(prev => [
              {
                ...prev[0],
                response: err?.message || '导入失败，请重试',
                status: 'error',
              },
            ]);
          })
          .finally(() => {
            setUploadPending(false);
          });
      }
    },
    [fileList, getList],
  );

  // --- 上传附件改变 ---
  const handleUploadFileChange = useCallback(({ fileList }) => {
    const f = fileList.slice(-1);
    setFileList(f);
  }, []);

  // --- 上传前验证 ---
  const handleBeforeUpload = useCallback(file => {
    const isExcel =
      file.type === 'application/vnd.ms-excel' ||
      file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (!isExcel) {
      message.warn('请上传Excel文件');
      return Upload.LIST_IGNORE;
    }

    return false;
  }, []);

  // --- 删除一条记录 ---
  const deleteItem = useCallback(
    params => {
      api.deleteItem(params).then(res => {
        if (res.success) {
          calcPageAfterDelete(1);
          getList();
        }
      });
    },
    [getList, calcPageAfterDelete],
  );

  // --- 批量删除记录 ---
  const batchDelete = useCallback(() => {
    Modal.confirm({
      title: '确认删除',
      content: '是否删除选中数据？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        return api
          .batchDelete({
            ids: selectedRowKeys.join(','),
          })
          .then(res => {
            if (res.success) {
              calcPageAfterDelete(selectedRowKeys.length);
              getList();
              setSelectedRowKeys([]);
            }
          });
      },
    });
  }, [calcPageAfterDelete, selectedRowKeys, getList]);

  const rowSelection = useMemo(
    () => ({
      onChange: selectedRowKeys => {
        setSelectedRowKeys(selectedRowKeys);
      },
      selectedRowKeys,
      preserveSelectedRowKeys: true,
      fixed: true,
    }),
    [selectedRowKeys],
  );

  const handleClearSelectedRowKeys = useCallback(() => {
    setSelectedRowKeys([]);
  }, [setSelectedRowKeys]);

  return {
    selectedRowKeys,
    setSelectedRowKeys,
    rowSelection,
    pagination: paginationRef.current,
    setPagination,
    extraParams: extraParamsRef.current,
    setExtraParams,
    list,
    setList,
    getList,
    deleteItem,
    batchDelete,
    downloadExcel,
    downloadPending,
    fileList,
    uploadExcel,
    uploadPending,
    handleUploadFileChange,
    handleBeforeUpload,
    loading,
    setLoading,
    handleClearSelectedRowKeys,
  };
}
